package 事务操作;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

public class Transaction2 {
    public static void main(String[] args) {
        String fkf = null;
        String skf = null;

        int rmb = 0;
        //接收用户输入Scanner
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入本次的转账金额:");
        rmb = sc.nextInt();
        System.out.println("请输入付款方id");
        fkf = sc.next();
        System.out.println("请输入收款方id");
        skf = sc.next();
        System.out.println("正在转账"+rmb+"元");
        String url = "jdbc:mysql://localhost:3306/db_jdbc_demo" +
                "?characterEncoding=utf8&useSSL=false&serverTimezone=UTC";
        String user = "root";
        String pass = "1234";
        Connection conn = null;
        Statement stmt = null;
        //2.高级版 preparedStatement pstmt = null;

        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url,user,pass);
            String sql1 = "update t_account set money = money - "+rmb+" where id = "+fkf;

            //2.高级版  String sql1 = "update t_account set money = money - ? where id = ?";

            String sql2 = "update t_account set money = money + "+rmb+" where id = "+skf;
            //开启事务
            conn.setAutoCommit(false);
            stmt = conn.createStatement();
            //2. 高级版 pstmt = conn.prepareStatement(sql2)
            //将sql1的？换成具体数据
            //pstmt.setInt(1,rmb); 第一个？
            //第二个？ pstmt.setString(2,skf);

            int i = stmt.executeUpdate(sql1);
//            int x = 5/0;
            int j = stmt.executeUpdate(sql2);
            if(i+j==2){
                System.out.println("转账成功！");
                conn.commit();
            }else{
                System.out.println("转账失败！");
            }

        } catch (Exception e) {
//            e.printStackTrace();
            System.out.println("转账出现异常！");
            try {
                conn.rollback();
            } catch (SQLException ex) {
                ex.printStackTrace();
            }

        }finally {
            try {
                stmt.close();
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }


    }
    }


